package net.wanho.commons.service.impl;

import net.wanho.commons.dao.BaseDAO;
import net.wanho.commons.exception.DAOException;
import net.wanho.commons.exception.ServiceException;
import net.wanho.commons.factory.BeanFactory;
import net.wanho.commons.service.BaseService;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

public abstract  class BaseServiceImpl<D extends BaseDAO,T> implements BaseService<T> {
    //默认DAO的实例  比如：LinkManDAO =  D
    protected D baseDAO ;

    public BaseServiceImpl() {
        //动态获得 泛型 参数类型
        Type genType = this.getClass().getGenericSuperclass();
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
        Class daoCls =  (Class)params[0];
        this.baseDAO = BeanFactory.getBean(daoCls) ;
    }

    @Override
    public boolean save(T entity) throws ServiceException {
        return baseDAO.insert(entity);
    }

    @Override
    public boolean remove(String id) throws ServiceException {
        return baseDAO.delete(id);
    }

    @Override
    public boolean modify(T entity) throws ServiceException {
        return baseDAO.update(entity);
    }

    @Override
    public T findById(String id) throws ServiceException {
        return (T) baseDAO.findById(id);
    }

    @Override
    public List<T> findAll() throws ServiceException {
        return baseDAO.selectAll();
    }

    @Override
    public List<T> findByCond(Map<String, String> condMap) throws DAOException {
        return baseDAO.selectByCond(condMap) ;
    }

    @Override
    public boolean modifyremove(T entity) throws ServiceException {
        return baseDAO.updelete(entity);
    }
}
